package com.heima.search.listen;

import com.heima.common.exception.CustException;
import com.heima.common.message.NewsUpOrDownConstants;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    @Autowired
    ArticleSearchService articleSearchService;

    @Autowired
    ArticleFeign articleFeign;

    @RabbitListener(queuesToDeclare = @Queue(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void handleUpMsg(String articleId) {
        log.info("成功接收文章上架消息 文章id{}", articleId);
        //向es中添加数据
        ResponseResult<SearchArticleVO> articleResult = articleFeign.findArticle(Long.valueOf(articleId));
        if (!articleResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程查询article文章数据失败");
        }
        SearchArticleVO articleVO = articleResult.getData();
        articleSearchService.saveArticle(articleVO);
    }

    @RabbitListener(queuesToDeclare = @Queue(NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void handleDownMsg(String articleId) {
        log.info("成功接收文章下架消息 文章id{}", articleId);
        //向es中删除数据
        articleSearchService.deleteArticle(articleId);


    }
}
